import { requestClient } from '#/api/request';

export namespace DemandApi {
  /** 需求信息 */
  export interface DemandInfo {
    id?: string;
    code: string;
    name: string;
    description?: string;
    status: 'draft' | 'pending' | 'approved' | 'rejected' | 'completed';
    priority: 'low' | 'medium' | 'high' | 'urgent';
    assignee?: string;
    createTime?: string;
    updateTime?: string;
    background?: string;
    requirements?: string;
    acceptance?: string;
    estimatedHours?: number;
    actualHours?: number;
    startDate?: string;
    endDate?: string;
    department?: string;
    category?: string;
    tags?: string[];
    attachments?: AttachmentInfo[];
    comments?: CommentInfo[];
    progress?: ProgressInfo[];
  }

  /** 附件信息 */
  export interface AttachmentInfo {
    id: string;
    name: string;
    url: string;
    size: number;
    type: string;
    uploadTime: string;
  }

  /** 评论信息 */
  export interface CommentInfo {
    id: string;
    content: string;
    author: string;
    createTime: string;
  }

  /** 进度信息 */
  export interface ProgressInfo {
    id: string;
    stage: string;
    status: 'pending' | 'in_progress' | 'completed';
    startTime?: string;
    endTime?: string;
    description?: string;
  }

  /** 需求列表查询参数 */
  export interface DemandListParams {
    pageNum?: number;
    pageSize?: number;
    code?: string;
    name?: string;
    status?: string;
    priority?: string;
    assignee?: string;
    department?: string;
    category?: string;
    startDate?: string;
    endDate?: string;
  }

  /** 需求统计信息 */
  export interface DemandStatistics {
    total: number;
    draft: number;
    pending: number;
    approved: number;
    rejected: number;
    completed: number;
    highPriority: number;
    urgentPriority: number;
    overdueCount: number;
    thisMonthCount: number;
  }
}

/**
 * 获取需求列表
 */
export function getDemandList(params?: DemandApi.DemandListParams) {
  return requestClient.get<{
    rows: DemandApi.DemandInfo[];
    total: number;
  }>('/operate/demand/list', { params });
}

/**
 * 获取需求详情
 */
export function getDemandDetail(id: string) {
  return requestClient.get<DemandApi.DemandInfo>(`/operate/demand/${id}`);
}

/**
 * 创建需求
 */
export function createDemand(data: Omit<DemandApi.DemandInfo, 'id' | 'createTime' | 'updateTime'>) {
  return requestClient.post<DemandApi.DemandInfo>('/operate/demand', data);
}

/**
 * 更新需求
 */
export function updateDemand(id: string, data: Partial<DemandApi.DemandInfo>) {
  return requestClient.put<DemandApi.DemandInfo>(`/operate/demand/${id}`, data);
}

/**
 * 删除需求
 */
export function deleteDemand(id: string) {
  return requestClient.delete(`/operate/demand/${id}`);
}

/**
 * 批量删除需求
 */
export function batchDeleteDemand(ids: string[]) {
  return requestClient.delete('/operate/demand/batch', { data: { ids } });
}

/**
 * 获取需求统计信息
 */
export function getDemandStatistics() {
  return requestClient.get<DemandApi.DemandStatistics>('/operate/demand/statistics');
}

/**
 * 更新需求状态
 */
export function updateDemandStatus(id: string, status: DemandApi.DemandInfo['status'], comment?: string) {
  return requestClient.put(`/operate/demand/${id}/status`, { status, comment });
}

/**
 * 分配需求
 */
export function assignDemand(id: string, assignee: string, comment?: string) {
  return requestClient.put(`/operate/demand/${id}/assign`, { assignee, comment });
}

/**
 * 添加需求评论
 */
export function addDemandComment(id: string, content: string) {
  return requestClient.post<DemandApi.CommentInfo>(`/operate/demand/${id}/comment`, { content });
}

/**
 * 上传需求附件
 */
export function uploadDemandAttachment(id: string, file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return requestClient.post<DemandApi.AttachmentInfo>(`/operate/demand/${id}/attachment`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
}

/**
 * 删除需求附件
 */
export function deleteDemandAttachment(demandId: string, attachmentId: string) {
  return requestClient.delete(`/operate/demand/${demandId}/attachment/${attachmentId}`);
}

/**
 * 更新需求进度
 */
export function updateDemandProgress(id: string, progress: Omit<DemandApi.ProgressInfo, 'id'>) {
  return requestClient.post<DemandApi.ProgressInfo>(`/operate/demand/${id}/progress`, progress);
}

/**
 * 导出需求数据
 */
export function exportDemandData(params?: DemandApi.DemandListParams) {
  return requestClient.get('/operate/demand/export', {
    params,
    responseType: 'blob'
  });
}

/**
 * 获取需求模板
 */
export function getDemandTemplate() {
  return requestClient.get('/operate/demand/template', {
    responseType: 'blob'
  });
}

// ==================== 销售数据相关API ====================

export namespace SalesDataApi {
  /** 销售数据信息 */
  export interface SalesDataInfo {
    地域: string;
    档位: string;
    品牌: string;
    种类: string;
    商品编码: string;
    商品名称: string;
    订货价: number;
    销售价: number;
    '2022_全年_销售额(元)': number;
    '2023_全年_销售额(元)': number;
    '2024_全年_销售额(元)': number;
  }

  /** 销售数据查询参数 */
  export interface SalesDataQuery {
    region?: string;
    grade?: string;
    brand?: string;
    category?: string;
    productName?: string;
    productCode?: string;
    pageNum?: number;
    pageSize?: number;
  }

  /** 下拉框选项 */
  export interface OptionsData {
    regions: string[];
    grades: string[];
    brands: string[];
    categories: string[];
  }
}

/**
 * 获取销售数据列表
 */
export function getSalesDataList(params?: SalesDataApi.SalesDataQuery) {
  // 构建SQL条件参数 (如果SQL中支持的话)
  const param = '';

  // 使用通用数据查询接口
  // 注意: dataCode需要在 http://172.24.0.1:5666/system/dataTable 中配置
  // 如果是销售额,可能是 'MonthlySales_year_amt' 或类似的code
  // 如果是销售量,使用 'MonthlySales_year_qty'
  const requestBody = {
    userId: 123,
    dataCode: 'MonthlySales_year_num',  // 年度需求销售量的dataCode
    param: param
  };

  return requestClient.post<{
    code: number;
    msg: string;
    data?: any;
  }>('/handle/data/getData', requestBody, {
    headers: {
      'Content-Type': 'application/json'
    }
  });
}

/**
 * 导出销售数据
 */
export function exportSalesData(params?: SalesDataApi.SalesDataQuery) {
  return requestClient.post<{
    code: number;
    msg: string;
    data?: any;
  }>('/operate/demand/sales/export', params);
}

/**
 * 获取所有下拉框选项
 */
export function getSalesDataOptions() {
  // 使用通用接口获取数据,然后提取唯一值
  const requestBody = {
    userId: 123,
    dataCode: 'MonthlySales_year_num',  // 与getSalesDataList使用同一个dataCode
    param: ''
  };

  return requestClient.post<{
    code: number;
    msg: string;
    data: any;
  }>('/handle/data/getData', requestBody, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res: any) => {
    // 从数据中提取唯一值
    const data = res.data || [];
    const regions = [...new Set(data.map((item: any) => item['地域'] || item['md05_product_yield_area']).filter(Boolean))];
    const grades = [...new Set(data.map((item: any) => item['档位'] || item['md05_product_grade_name']).filter(Boolean))];
    const brands = [...new Set(data.map((item: any) => item['品牌'] || item['md05_product_brand_name']).filter(Boolean))];
    const categories = [...new Set(data.map((item: any) => item['种类'] || item['md05_product_type']).filter(Boolean))];

    return {
      ...res,
      data: {
        regions,
        grades,
        brands,
        categories
      }
    };
  });
}

/**
 * 搜索商品名称
 */
export function searchProducts(keyword?: string) {
  if (!keyword) {
    return Promise.resolve({ code: 200, msg: 'success', data: [] });
  }

  // 使用通用接口获取数据,然后过滤商品名称
  const requestBody = {
    userId: 123,
    dataCode: 'MonthlySales_year_num',  // 与getSalesDataList使用同一个dataCode
    param: ''
  };

  return requestClient.post<{
    code: number;
    msg: string;
    data: any;
  }>('/handle/data/getData', requestBody, {
    headers: {
      'Content-Type': 'application/json'
    }
  }).then((res: any) => {
    // 提取商品名称的唯一值并过滤
    const data = res.data || [];
    const allProducts = data.map((item: any) => item['商品名称'] || item['md05_product_name']).filter(Boolean);
    const products = [...new Set(allProducts.filter((name: string) => name.includes(keyword)))];

    return {
      ...res,
      data: products.slice(0, 20) // 限制返回20个结果
    };
  });
}

/**
 * 获取地域列表
 */
export function getRegions() {
  return requestClient.get<{
    code: number;
    msg: string;
    data: string[];
  }>('/operate/demand/sales/regions');
}

/**
 * 获取档位列表
 */
export function getGrades() {
  return requestClient.get<{
    code: number;
    msg: string;
    data: string[];
  }>('/operate/demand/sales/grades');
}

/**
 * 获取品牌列表
 */
export function getBrands() {
  return requestClient.get<{
    code: number;
    msg: string;
    data: string[];
  }>('/operate/demand/sales/brands');
}

/**
 * 获取种类列表
 */
export function getCategories() {
  return requestClient.get<{
    code: number;
    msg: string;
    data: string[];
  }>('/operate/demand/sales/categories');
}


